<template>
  <div class="version-script-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/script_library' }">脚本库</el-breadcrumb-item>
        <el-breadcrumb-item>版本管理 - {{ scriptInfo.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 脚本信息卡片 -->
    <el-card class="script-info-card">
      <div class="script-info-content">
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">脚本名称：</span>
            <div class="name-edit-container">
        <template v-if="!isEditingName">
          <span class="info-value name-display">{{ scriptInfo.name }}</span>
          <el-button 
            link 
            size="small" 
            class="edit-btn"
            @click="startEditName"
          >
            <i class="el-icon-edit"></i>
          </el-button>
        </template>
        <template v-else>
          <el-input
            v-model="tempName"
            size="small"
            class="name-input"
            @blur="handleNameBlur"
            @keyup.enter="saveName"
            @keyup.esc="cancelEditName"
            ref="nameInputRef"
          ></el-input>
          <div class="name-edit-actions">
            <el-button type="primary" size="small" @click="saveName">保存</el-button>
            <el-button size="small" @click="cancelEditName">取消</el-button>
          </div>
        </template>
      </div>
          </div>
          <div class="info-item">
            <span class="info-label">脚本语言：</span>
            <span class="info-value">{{ scriptInfo.script_type }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">场景标签：</span>
            <span class="info-value">{{ scriptInfo_tag.name || '无' }}</span>
          </div>
        </div>
        
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">更新人：</span>
            <span class="info-value">{{ scriptInfo.modify_user || '无' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">更新时间：</span>
            <span class="info-value">{{ scriptInfo.modify_time || '无' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">脚本描述：</span>
            <span class="info-value">{{ scriptInfo.description || '无' }}</span>
          </div>
        </div>
        
      </div>
    </el-card>
    <el-button type="primary" size="small" @click="addVersion">新建版本</el-button>
    <el-button type="primary" size="small" @click="comparisonVersion">版本对比</el-button>
    <!-- 版本列表表格 -->
    <el-card class="version-table-card">
      
    <KyTable 
        ref="tableRef" 
        :getData="scriptVersion" 
        :showSelect="showSelect"
      >
        <template #table-action>
          <div class="os-upgrade-table-action">
            <!-- 设置 -->
            <el-button class="kylin-item-button" @click.stop="handleCustomColumn" name="plugin-os-upgrade:operation">
              <el-icon><Setting /></el-icon>
            </el-button>
          </div>
        </template>
        <!-- table表格 -->
        <template #table>
          <el-table-column
            prop="version"
            :label="'版本号'"
          />
           <!-- <el-table-column
            prop="targetSystem"
            :label="'被引用'"
          /> -->
          <el-table-column
            prop="modify_user"
            :label="'更新人'"
          />
          <el-table-column
            prop="modify_time"
            :label="'更新时间'"
          />
          <el-table-column
            prop="status"
            :label="'状态'"
          />
          <el-table-column
            prop="targetSystem"
            :label="'操作'"
          >
            <template #default="scope" >
              <el-button type="link" size="small" @click="publishVersion(scope.row)">上线</el-button>
              <el-button type="link" size="small">禁用</el-button>
              <el-button type="link" size="small">编辑</el-button>
              <el-button type="link" size="small">克隆</el-button>
              <el-button type="link" size="small">去执行</el-button>
              <el-button type="link" size="small" @click="deleteVersion(scope.row)">删除</el-button>
            </template>

          </el-table-column>
        </template>
        
        <template #empty>
          <div>
            <span role="button" class="link-btn" @click="addScript">
              创建一个脚本吧!
            </span>
          </div>
        </template>
    </KyTable>
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        :before-close="handleCloseDialog"
        :width="dialogWidth"
      >
        <CustomColumn
            v-if="rwType === 'custom_list'"
            @click="handleCloseDialog"
            :customData="colData"
            :rawData="rawData"
            @handleOk="handleCustomColumnOk"
          ></CustomColumn>
        
    </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref,defineAsyncComponent, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router'
import { scriptVersion,scriptVersionPublish,scriptVersionDel } from '@/api/scriptLibrary';
const CustomColumn = defineAsyncComponent(() => import('@/components/customColumn/index.vue'));
const KyTable = defineAsyncComponent(() => import('@/components/KyTable/index.vue'));


const router = useRouter();
const route = useRoute();
const dialogVisible = ref<boolean>(false);
const dialogTitle = ref<string>('自定义列');
const dialogWidth = ref<string>('50%');
const rwType = ref<string>('custom_list');
const colData = ref<any>([]);
const rawData = ref<any>([]);
const tableRef = ref(null);
const showSelect = ref<boolean>(true); // 定义是否显示选择框
// 脚本详情信息
const scriptInfo:any = route.query
const scriptInfo_tag = JSON.parse(scriptInfo.tag)
console.log('[ scriptInfo ] >', scriptInfo,scriptInfo_tag)

const handleCustomColumn = (row: any) => {
  // console.log('[ 自定义列 ] >', '自定义列');
    getCustomColumnFun()
    rwType.value = 'custom_list';
    dialogVisible.value = true;
    dialogTitle.value = '自定义列';
};
const getCustomColumnFun = async( ) => {
  
  colData.value = [
    { name: 'action', label: '脚本名称1111' },
    { name: 'ip', label: '脚本语言' },
    { name: 'originalSystem', label: '场景标签' },
    { name: 'targetSystem', label: '被引用' },
    { name: 'targetSystem', label: '线上版本' },
    { name: 'targetSystem', label: '更新人' },
    { name: 'targetSystem', label: '更新时间' },
  ]



  // const userId = getUserId()
  //   if (userId) {
  //     const res = await getCustomColumn(userId)
  //     if (res.data.data && res.data.data.length == rawData.value.length && res.data.data[res.data.data.length - 1].name == 'groupName') {
  //       colData.value = res.data.data;
  //     } else {
  //       colData.value = rawData;
  //     }
  //   } else {
  //     colData.value = rawData;
  //   }
}
// 确保在组件挂载时获取脚本详情
onMounted(() => {
});


const handleCloseDialog = () => {
  dialogVisible.value = false;
  rwType.value = '';
};
const handleCustomColumnOk = (val: any) => {
  console.log(val);
  handleCloseDialog();
}
const addScript = () => { 
  router.push('/script_library/addScript')
}
const isEditingName = ref()
const tempName = ref()
const nameInputRef = ref()
// 开始编辑脚本名称
const startEditName = () => {
  isEditingName.value = true;
  tempName.value = scriptInfo.value.name || '';
  // 等待DOM更新后聚焦输入框
  setTimeout(() => {
    if (nameInputRef.value) {
      nameInputRef.value.focus();
    }
  }, 0);
};

// 处理输入框失焦
const handleNameBlur = () => {
  // 失焦时自动保存
  saveName();
};

// 保存脚本名称
const saveName = async () => {
  const newName = tempName.value.trim();
  if (!newName) {
    // 如果名称为空，使用原值
    tempName.value = scriptInfo.value.name || '';
    cancelEditName();
    return;
  }
  
  try {
    // 这里可以添加API调用来更新脚本名称
    // const res = await updateScriptName(route.params.id as string, newName);
    // if (res.data.code === 0 || res.data.code === '0' || res.data.code === 200) {
    //   scriptInfo.value.name = newName;
    // }
    
    // 临时直接更新本地数据
    scriptInfo.value.name = newName;
    isEditingName.value = false;
    
    // 显示成功提示
    ElMessage.success('脚本名称更新成功');
  } catch (error) {
    console.error('更新脚本名称失败:', error);
    ElMessage.error('更新脚本名称失败，请重试');
  }
};
const deleteVersion = async (row:any) => {
  try {
    const res = await scriptVersionDel({
      id: row.id
    });
    if (res.data.code === 200) {
      ElMessage.success('已删除');
      // 刷新当前页面
      router.go(0);
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    ElMessage.error('删除失败，请重试');
  }
}
const publishVersion = async (row: any) => {
  try {
    const res = await scriptVersionPublish({
      id: row.id,
      new_status: '已发布',
    });
    if (res.data.code === 200) {
      ElMessage.success('上线成功');
      // 刷新当前页面
      router.go(0);
    } else {
      ElMessage.error(res.data.msg || '上线失败');
    }
  } catch (error) {
    console.error('上线失败:', error);
    ElMessage.error('上线失败，请重试');
  }
}
// 取消编辑
const cancelEditName = () => {
  isEditingName.value = false;
  tempName.value = '';
};
// 新建版本
const addVersion = () => {
  console.log('[ route.query ] >', route.query)
  router.push({path:'/script_library/addVersion',query:route.query})

}
// 版本对比
const comparisonVersion = () => {
}

</script>

<style scoped>
.version-script-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.script-info-card {
  margin-bottom: 20px;
}

.script-info-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.script-info-header h2 {
  margin: 0 0 0 20px;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.script-info-content {
  padding-left: 0;
}

.info-row {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.info-item {
  width: 32%;
  display: flex;
  align-items: center;
}

.info-label {
  color: #606266;
  margin-right: 10px;
  width: 100px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  font-weight: 400;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.name-edit-container {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.name-display {
  flex: 1;
  margin-right: 8px;
}

.edit-btn {
  opacity: 0;
  margin-left: 8px;
  color: #409eff !important;
  transition: opacity 0.2s ease;
  font-size: 14px;
}

.name-edit-container:hover .edit-btn {
  opacity: 1;
}

.name-input {
  flex: 1;
  margin-right: 8px;
}

.name-edit-actions {
  display: flex;
  gap: 8px;
}

.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.search-area {
  margin-bottom: 20px;
}

.search-input {
  width: 500px;
}

.version-table-card {
  margin: 20px 0;
}

.version-text {
  font-weight: 500;
  color: #409eff;
}

.description-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>